'use strict';
const debug = require('debug')('koa-grace:i18n');
const error = require('debug')('koa-grace-error:i18n');

//todo 注册ctx的i18n函数和filter
module.exports = function(options) {
	if(!options){
		throw new Error('i18n config required.');
	}	
	const locales = options.locales;
	const cookieKey = options.cookieKey;
	const queryKey = options.queryKey;
	const defaultLocale = options.locale || locales[0] || 'en-us';

	const formatLocale = function(locale) {
		// support zh_CN, en_US => zh-CN, en-US
		var key = locale.replace('_', '-').toLowerCase();
		if(locales[key]) {
			return locales[key]
		}
		return defaultLocale;
	};

	return {
		getLocaleFromQuery : function(request) {
			return formatLocale(request.query[queryKey]);
		},
		getLocaleFromSubdomain : function(request) {
			return formatLocale(request.subdomains.pop());
		},
		getLocaleFromHeader : function(request) {
			var accept = request.acceptsLanguages() || '',
	        reg = /(^|,\s*)([a-z-]+)/gi,
					localesKey = [],
					match	;
			while ((match = reg.exec(accept))) {
				localesKey.push(match[2])
				if (localesKey.length) {
				break;
				}
			}
			return formatLocale(localesKey[0]);
		},
		getLocaleFromCookie : function(request) {
			return formatLocale(request.ctx.cookies.get(cookieKey));
		},
		getLocaleFromUrl : function(request) {
			var segments = request.path.substring(1).split('/');
      		return formatLocale(segments[options && options.offset || 0]);
		},
		getLocaleFromTLD : function(request) {
			return formatLocale(request.hostname.split('.').pop());
		},
	}
}
